﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class CameraRatioExpand : MonoBehaviour
{
    public int ReferenceWidth;
    public int ReferenceHeight;
    public float DesignFieldOfView;

    Camera _camera;
    float _referenceAspectRatio;
    float _referenceWidthFOV;

    void OnEnable()
    {
        _camera = GetComponent<Camera>();
        _referenceAspectRatio = 1.0f * ReferenceWidth / ReferenceHeight;
        _referenceWidthFOV = _referenceAspectRatio * DesignFieldOfView;
        CalculateFOV();
    }

#if UNITY_EDITOR
    void Update()
    {
        CalculateFOV();
    }
#endif


    void CalculateFOV()
    {
        float screenFov = 1.0f * Screen.width / Screen.height;
        if (screenFov >= _referenceAspectRatio)
        {
            _camera.ResetAspect();
            _camera.fieldOfView = DesignFieldOfView;
        }
        else
        {
            float hFOVInRads = _referenceWidthFOV * Mathf.Deg2Rad;
            float vFOVInRads = 2 * Mathf.Atan(Mathf.Tan(hFOVInRads / 2) / screenFov);
            float vFOV = vFOVInRads * Mathf.Rad2Deg;
            _camera.aspect = screenFov;
            _camera.fieldOfView = vFOV;
        }
    }
}
